// StringExtractor.java
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StringExtractor {
    private State currentState;
    private List<String> extractedStrings = new ArrayList<>();
    private StringBuilder currentString = new StringBuilder();

    public StringExtractor() {
        this.currentState = new InitialState();
    }

    // 处理单个字符
    public void processChar(char c) {
        currentState.handleChar(this, c);
    }

    // 添加提取到的字符串
    public void addString(String str) {
        extractedStrings.add(str);
        System.out.println("提取字符串: \"" + str + "\"");
    }

    // 获取所有提取的字符串
    public List<String> getExtractedStrings() {
        return extractedStrings;
    }

    // 读取文件并提取字符串
    public void extractFromFile(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            int c;
            while ((c = reader.read()) != -1) {
                processChar((char) c);
            }
            // 文件结束
            if (currentString.length() > 0) {
                System.err.println("未闭合的字符串：" + currentString.toString());
                currentString.setLength(0);
            }
        } catch (IOException e) {
            System.err.println("读取文件失败：" + e.getMessage());
        }
    }

    // 设置状态
    public void setState(State state) {
        this.currentState = state;
    }

    // 添加字符到当前字符串
    public void appendChar(char c) {
        currentString.append(c);
    }

    // 清空当前字符串
    public void clearCurrentString() {
        currentString.setLength(0);
    }

    // 获取当前字符串内容
    public String getCurrentString() {
        return currentString.toString();
    }

    // 主方法测试
    public static void main(String[] args) {
        StringExtractor extractor = new StringExtractor();
        extractor.extractFromFile("source.java"); // 假设文件名为 source.java
    }
}